<template>
  <div>
    <Content
      @InputFn="InputFn"
      @QueryFn="QueryFn"
      @OpenDiaFn="OpenDiaFn"
      @OneBtn="OneBtn"
      @TwoBtn="TwoBtn"
      @CheckDetailsFn="CheckDetailsFn"
      @headerStyleEvent="headerStyleEvent"
    />
    <ADDdialog :title="name" :nodeOneDialog="nodeOneDialog" @CloseDia="CloseDiaFn" @OpenDia="OpenDia" @OpenDiaFn="OpenDiaFn">
      <template #nodeNew>
         <!-- 表单内容 -->
         <el-form
            ref="departRef"
            :model="FromData"
            label-width="100px"
            :rules="departRules"
            size="small"
          >
            <el-form-item label="点位名称:" prop="name" width="100px">
              <el-input placeholder="请输入" v-model="FromData.name"/>
            </el-form-item>
            <el-form-item label="所在区域:" prop="regionId" >
              <el-select v-model="FromData.regionId" placeholder="请选择" style="width: 100%;">
                <el-option
                v-for="(item, index) in PropsData.DropDown" :key="index"
                  :label="item.statusName"
                  :value="item.statusId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属商圈:" prop="businessId" >
              <el-select v-model="FromData.businessId" placeholder="请选择" style="width: 100%;" >
                <el-option
                  v-for="(item, index) in BusinessCircleData" :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
             <el-form-item label="归属合作商:" prop="ownerId" >
              <el-select v-model="FromData.ownerId" placeholder="请选择" style="width: 100%;">
                <el-option
                v-for="(item, index) in PartnersData" :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址:" prop="addr">
              <el-cascader
                  size="large"
                  :options="options"
                  v-model="selectedOptions"
                  @change="handleChange"
                  style="width: 100%;"
                >
                </el-cascader>
            </el-form-item>
            <el-form-item  prop="remark">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入详细地址"
                v-model="FromData.remark"
                :autosize="{ minRows: 4, maxRows: 5}">
              </el-input>
            </el-form-item>
          </el-form>
      </template>
    </ADDdialog>
    <ADDdialog title="点位详情" :nodeTwoDialog="nodeTwoDialog" @CloseDia="CloseDiaFn">
      <template #nodeMsg>
        <el-table :data="Point" :header-cell-style="headerStyleEvent">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="机器编号" prop="innerCode"></el-table-column>
          <el-table-column label="设备状态" prop="vmStatus">
            <template #default="{ row }">
              {{ row.vmStatus ? row.vmStatus === 1 ? '运营' : '撤机' : '未投放' }}
            </template>
          </el-table-column>
          <el-table-column label="最后一次的供货时间" prop="lastSupplyTime">
            <template #default="{ row }">
              {{ Timer(row) || ''}}
            </template>
          </el-table-column>
        </el-table>
      </template>
    </ADDdialog>
    <ADDdialog title="修改点位" :nodeTreeDialog="nodeTreeDialog" @CloseDia="CloseDiaFn"  @OpenDiaFn="OpenDiaFn">
      <template #nodeModify>
        123
      </template>
    </ADDdialog>
  </div>
</template>

<script>
import {
  MsgRegionalRequest, RegionalListRequest, BusinessCircleListRequest, PartnersListRequest, NewPointListRequest,
  PointMsgListRequest, PointModifyListRequest
} from '@/api'
import { createNamespacedHelpers } from 'vuex'
import { regionData, CodeToText } from 'element-china-area-data'
import dayjs from 'dayjs'
const { mapMutations, mapState } = createNamespacedHelpers('publics')
export default {
  data () {
    return {
      nodeOneDialog: false,
      nodeTwoDialog: false,
      nodeTreeDialog: false,
      page: {
        pageIndex: 1,
        pageSize: 10,
        name: null,
        regionId: null
      },
      FromData: {
        name: '',
        addr: '',
        areaCode: '',
        createUserId: this.$store.state.user.UserLoginData.userId,
        regionId: '',
        businessId: '',
        ownerId: '',
        ownerName: '',
        // 详细地址
        remark: ''
      },
      // 点位完整数据
      PointAll: [],
      // 弹窗标题
      name: '新增点位',
      // 城市下拉菜单选项
      options: regionData,
      selectedOptions: [],
      // 校验
      departRules: {
        name: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] },
          { min: 1, max: 15, message: '1 - 15个字符', trigger: ['blur', 'change'] }
        ],
        addr: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] },
          { min: 1, max: 40, message: '1 - 40个字符', trigger: ['blur', 'change'] }
        ],
        regionId: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] },
          { min: 1, max: 40, message: '1 - 40个字符', trigger: ['blur', 'change'] }
        ],
        businessId: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] }
        ],
        ownerId: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] }
        ],
        remark: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] },
          { min: 1, max: 40, message: '1 - 40个字符', trigger: ['blur', 'change'] }
        ]
      },
      // 商圈列表
      BusinessCircleData: [],
      // 合作商
      PartnersData: [],
      // 点位详情
      Point: []
    }
  },
  async created () {
    this.nodelist()
    this.AreaSoFn()
  },
  methods: {
    ...mapMutations(['MaOrder', 'MaAddnum', 'MaAeenum', 'MaNum', 'MaDropDown']),
    // 表格头回调函数
    headerStyleEvent () {
      return 'background-color:#f3f6fb'
    },
    // 页面列表
    async nodelist () {
      const res = await MsgRegionalRequest(this.page)
      const dataNew = []
      res.data.currentPageRecords.map(item => {
        const obj = {
          taskCode: item.name,
          innerCode: item.region.name,
          taskType: { typeName: item.businessType.name },
          taskStatusTypeEntity: { statusName: item.ownerName },
          userName: item.addr.split('-').at(-1),
          id: Number(item.id)
        }
        dataNew.push(obj)
      })
      console.log(res)
      this.PointAll = res.data.currentPageRecords
      // 转换数据
      this.MaOrder({
        currentPageRecords: dataNew,
        totalCount: res.data.totalCount,
        totalPage: res.data.totalPage
      }
      )
    },
    // 区域搜索
    async AreaSoFn () {
      const res = await RegionalListRequest({
        ...this.page,
        pageSize: 100000
      })
      const newArr = JSON.parse(JSON.stringify(res.data.currentPageRecords).replace(/id/g, 'statusId').replace(/name/g, 'statusName'))
      this.MaDropDown(newArr)
    },
    OneBtn () {
      this.MaAeenum()
      this.page.pageIndex--
      this.nodelist()
    },
    TwoBtn () {
      this.MaAddnum()
      this.page.pageIndex++
      this.nodelist()
    },
    // 打开弹窗时
    async OpenDiaFn (item) {
      console.log(this.FromData)
      this.nodeOneDialog = true
      // 商圈列表
      const res = await BusinessCircleListRequest()
      this.BusinessCircleData = res.data
      // 合作商
      const res1 = await PartnersListRequest({ ...this.page, pageSize: 10000 })
      this.PartnersData = res1.data.currentPageRecords
      console.log(this.PartnersData, this.FromData.ownerId)
    },
    // 关闭弹窗时
    CloseDiaFn () {
      this.nodeOneDialog = false
      this.nodeTwoDialog = false
      console.log(this.$refs.departRef)
      this.name = '新增点位'
      this.$refs.departRef.resetFields()
      this.FromData = {}
    },
    // 弹窗确定
    async OpenDia (item) {
      this.$refs.departRef.validate(async (vali) => {
        if (vali) {
          if (item === '9') {
            this.FromData.ownerName = this.PartnersData.filter(item => item.id === this.FromData.ownerId)[0].name
            this.FromData.addr += this.FromData.remark
            if (this.name === '新增点位') {
              try {
                await NewPointListRequest(this.FromData)
                this.$message.success('新增成功')
                this.CloseDiaFn()
                this.nodelist()
              } catch (err) {
                this.$message.error('新增失败')
              }
            } else {
              try {
                await PointModifyListRequest(this.FromData)
                this.$message.success('修改成功')
                this.CloseDiaFn()
                this.nodelist()
              } catch (err) {
                this.$message.error('修改失败')
              }
            }
          }
        }
      })
    },
    // 查询
    async QueryFn () {
      this.page = {
        name: this.PropsData.Order.taskCode,
        regionId: this.PropsData.Order.status
      }
      this.nodelist()
    },
    // 操作按钮
    async CheckDetailsFn (item, num) {
      console.log(item)
      if (num === '1') {
        this.nodeTwoDialog = true
        const res = await PointMsgListRequest(item.id)
        this.Point = res.data
      }
      if (num === '2') {
        this.nodeOneDialog = true
        this.nodelist()
        this.name = '点位修改'
        const a = this.PointAll.filter(i => Number(i.id) === item.id)
        this.FromData = a[0]
        console.log(item, this.PointAll)
      }
      if (num === '3') {
        this.$notify({
          title: '提示',
          message: '演示操作，不支持此操作',
          type: 'warning'
        })
      }
    },
    InputFn (a, b) {
      console.log(this.PropsData.Order)
    },
    // 城市下拉菜单
    handleChange (val) {
      var loc = ''
      for (let i = 0; i < this.selectedOptions.length; i++) {
        loc += CodeToText[this.selectedOptions[i]] + '-'
      }
      this.FromData.addr = loc
      this.FromData.areaCode = val.at(-1)
    },
    Timer (item) {
      return dayjs(item.lastSupplyTime).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  computed: {
    ...mapState(['PropsData'])
  }
}
</script>

<style></style>
